package com.example.administrator.caigou51.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.util.AbViewUtil;
import com.alibaba.fastjson.JSON;
import com.example.administrator.caigou51.EventBusClass.GotoFragment;
import com.example.administrator.caigou51.EventBusClass.UpdateGoodsDetail;
import com.example.administrator.caigou51.EventBusClass.UpdateGoodsDetailViewPager;
import com.example.administrator.caigou51.EventBusClass.UpdateShopCarRedCount;
import com.example.administrator.caigou51.R;
import com.example.administrator.caigou51.bean.CollectBean;
import com.example.administrator.caigou51.bean.GoodsDetailBean;
import com.example.administrator.caigou51.bean.MainDataBean;
import com.example.administrator.caigou51.control.DialogGoodsBuy;
import com.example.administrator.caigou51.fragment.GoodsInfoFragment;
import com.example.administrator.caigou51.fragment.SayBooksFragment;
import com.example.administrator.caigou51.global.App;
import com.example.administrator.caigou51.global.Constant;
import com.example.administrator.caigou51.request.BaseResponse;
import com.example.administrator.caigou51.request.ICallBackForRequestServer;
import com.example.administrator.caigou51.request.RequestServerManager;
import com.example.administrator.caigou51.util.AnimUtils;
import com.example.administrator.caigou51.util.ToastUtil;
import com.example.administrator.caigou51.widget.dialog.SweetDialogManager;


import java.io.Serializable;
import java.util.ArrayList;

import cn.pedant.SweetAlert.SweetAlertDialog;
import cn.xiaoneng.activity.ChatActivity;
import de.greenrobot.event.EventBus;


/**
 * Created by Administrator on 2015/9/10.
 */
public class GoodsDetailsActivity extends GBaseActivity implements View.OnClickListener,ViewPager.OnPageChangeListener {
    private android.support.v4.view.ViewPager viewPager_viewpager;
    private ArrayList<Fragment> list;
    GoodsFragmentAdapter fragmentAdapter;
    private ImageView imageViewMore,imageViewGreenLine,imageViewGoBack;
    private float temp = 0;
    private TextView textViewShangPing,textViewXiangQing;
    private RelativeLayout relativeLayoutShopCar;
    private TextView textViewBuyNow;
    private TextView textViewAddCart;
    private DialogGoodsBuy dialogGoodsBuy;
    private AnimUtils mAnimUtils;
    private ImageView imageViewCart,imageViewAnim,imageViewZhiXun,imageViewShouCang;
    public static final String GOODSID="GOODSID";
    public static final String TagGoodsDetailBean="TagGoodsDetailBean";
    private GoodsDetailBean goodsDetailBean;
    private TextView textViewShopCarCount;
    private String itemID;
    private int goodsCount=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentViewFor720_1280(R.layout.activity_goods_detail);
        //网页调用打开app
        Uri uridata = this.getIntent().getData();
        if (uridata!=null)
        itemID = uridata.getQueryParameter("itemid");

        findViewByIds();
        initDatas();
        EventBus.getDefault().register(this);

    }



    protected void findViewByIds() {
        relativeLayoutShopCar= (RelativeLayout) findViewById(R.id.relativeLayoutShopCar);
        imageViewGoBack= (ImageView) findViewById(R.id.imageViewGoBack);imageViewGoBack.setOnClickListener(this);
        viewPager_viewpager= (ViewPager) findViewById(R.id. viewPager_viewpager);viewPager_viewpager.setOnPageChangeListener(this);
        imageViewGreenLine= (ImageView) findViewById(R.id.imageViewGreenLine);
        imageViewMore= (ImageView) findViewById(R.id.imageViewMore);
        imageViewMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                App.showPopupWindow(imageViewMore,GoodsDetailsActivity.this,-124,-30);
            }
        });

        textViewShangPing= (TextView) findViewById(R.id.textViewShangPing);textViewShangPing.setOnClickListener(this);
        textViewXiangQing= (TextView) findViewById(R.id.textViewXiangQing);textViewXiangQing.setOnClickListener(this);
       // textViewPingJia= (TextView) findViewById(R.id.textViewPingJia);textViewPingJia.setOnClickListener(this);

        textViewBuyNow= (TextView)findViewById(R.id.textViewBuyNow);textViewBuyNow.setOnClickListener(this);
        textViewAddCart=(TextView)findViewById(R.id.textViewAddCart);textViewAddCart.setOnClickListener(this);
        textViewShopCarCount= (TextView) findViewById(R.id.textViewShopCarCount);
        imageViewCart= (ImageView) findViewById(R.id.imageViewCart);imageViewCart.setOnClickListener(this);
        imageViewZhiXun = (ImageView) findViewById(R.id.imageViewZhiXun);imageViewZhiXun.setOnClickListener(this);
        imageViewShouCang = (ImageView) findViewById(R.id.imageViewShouCang);imageViewShouCang.setOnClickListener(this);
    }


    protected void initDatas() {
        getTopBar().setVisibility(View.GONE);
        if (TextUtils.isEmpty(itemID)) {
            itemID = getIntent().getStringExtra(GOODSID);
        }
        list = new ArrayList<Fragment>();
        list.add(new GoodsInfoFragment(itemID));
        list.add(new SayBooksFragment(itemID));
    //    list.add(new SayBooksFragment());
    //    list.add(new GoodsPingJiaFragment());
        fragmentAdapter = new GoodsFragmentAdapter(this.getSupportFragmentManager(), list);
        viewPager_viewpager.setAdapter(fragmentAdapter);
        viewPager_viewpager.setOffscreenPageLimit(GoodsFragmentAdapter.COUNT);

        imageViewAnim=new ImageView(getActivity());
        imageViewAnim.setLayoutParams(new ViewGroup.LayoutParams(AbViewUtil.scaleValue(getActivity(),60), AbViewUtil.scaleValue(getActivity(),60)));
        imageViewAnim.setImageResource(R.drawable.test_3);
        GBaseActivity.RefreshShopCarRedCount(textViewShopCarCount,relativeLayoutShopCar);

        //判断是否认证成功，是否有库存
        judgeLoginState();

    }



    private boolean isRepeatCollect()
    {
        for (int i=0;i<App.getCollectBeanListServer().size();i++)
        {
            if (goodsDetailBean.getItemid().equals(App.getCollectBeanListServer().get(i).getItemid()))
            {
                return true;
            }
        }
        return  false;
    }


    protected void fillArrayInListView() {

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId())
        {
            case R.id.imageViewGoBack:
                finish();
                break;
            case R.id.imageViewCart:
                Intent intent4 = new Intent(this,MainActivity.class);
                startActivity(intent4);
                EventBus.getDefault().post(new GotoFragment(MainActivity.TAB_GouWuChe));
                finish();
                break;
            case R.id.imageViewShouCang:
                if (App.getUserBean()!=null) {
                    if (isRepeatCollect())
                    {
                        ToastUtil.showToast("您已加入收藏");
                    }else
                    {
                        TaskCollectGoods(false);
                    }

                }else
                {
                    Intent intent=new Intent(GoodsDetailsActivity.this,LoginActivity.class);
                    startActivity(intent);
                }
              /*  Intent intent=new Intent(GoodsDetailsActivity.this,CollectActivity.class);
                startActivity(intent);*/
                break;
            case R.id.imageViewZhiXun:
               GoToChat();
                break;
            case R.id.textViewAddCart:

                dialogGoodsBuy = new DialogGoodsBuy(getActivity(),goodsDetailBean,dialogGoodsBuy.AddCar);

                if (!dialogGoodsBuy.isShowing()) {


                    WindowManager.LayoutParams lp = dialogGoodsBuy.getWindow().getAttributes();
                    lp.width = (int)(App.getInstance().screenWidth); //设置宽度
                    dialogGoodsBuy.getWindow().setAttributes(lp);

                    Window window = dialogGoodsBuy.getWindow();
                    window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
                    window.setWindowAnimations(R.style.AnimBottom);  //添加动画
                    dialogGoodsBuy.show();
                }
                break;
            case R.id.textViewBuyNow:
                //判断，如果有多个规格就弹出dialog
               /* Intent intent=new Intent(getActivity(), CheckOrderActivity.class);
                startActivity(intent);*/

                dialogGoodsBuy = new DialogGoodsBuy(getActivity(),goodsDetailBean,DialogGoodsBuy.BugNowTag);

                if (!dialogGoodsBuy.isShowing()) {


                    WindowManager.LayoutParams lp = dialogGoodsBuy.getWindow().getAttributes();
                    lp.width = (int)(App.getInstance().screenWidth); //设置宽度
                    dialogGoodsBuy.getWindow().setAttributes(lp);

                    Window window = dialogGoodsBuy.getWindow();
                    window.setGravity(Gravity.BOTTOM);  //此处可以设置dialog显示的位置
                    window.setWindowAnimations(R.style.AnimBottom);  //添加动画
                    dialogGoodsBuy.show();
                }
                break;
            case R.id.textViewShangPing:
                viewPager_viewpager.setCurrentItem(0);
                break;
            case R.id.textViewXiangQing:
                viewPager_viewpager.setCurrentItem(1);
                break;
        }

    }
    public void onEventMainThread(UpdateGoodsDetailViewPager updateGoodsDetailViewPager) {
        viewPager_viewpager.setCurrentItem(updateGoodsDetailViewPager.index);
    }
    public void onEventMainThread(UpdateGoodsDetail updateGoodsDetail) {
       this.goodsDetailBean=updateGoodsDetail.goodsDetailBean;

        judgeLoginState();
        //判断是否已收藏
        if (isRepeatCollect())
        {
            imageViewShouCang.setImageResource(R.drawable.icon_love);
        }else
        {
            imageViewShouCang.setImageResource(R.drawable.icon_love_grey);
        }
        saveMyFoot(this.goodsDetailBean);
    }
    private void saveMyFoot(GoodsDetailBean goodsDetailBean) {
        CollectBean collectBean=new CollectBean();
        collectBean.setItemid(goodsDetailBean.getItemid());
        collectBean.setCorporation(goodsDetailBean.getCorporation());
        if (goodsDetailBean.getImages()!=null) {
            collectBean.setThumb(goodsDetailBean.getImages().get(0));
        }
        collectBean.setPrice(goodsDetailBean.getPrice());
        collectBean.setShip_price(goodsDetailBean.getShip_price());
        collectBean.setTitle(goodsDetailBean.getTitle());
        collectBean.setCollect_id(goodsDetailBean.getItemid());
        collectBean.setPromotion(goodsDetailBean.getPromotion());
        collectBean.setPromotion_price(goodsDetailBean.getPromotion_price());
        collectBean.setProduct_spec(goodsDetailBean.getProduct_spec());
        //去重
        boolean isRepeat=false;
        for (int i=0;i< App.getCollectBeanList().size();i++)
        {
            if (goodsDetailBean.getItemid().equals(App.getCollectBeanList().get(i).getItemid()))
                isRepeat=true;
        }
        if (!isRepeat) {
            App.getCollectBeanList().add(collectBean);
            App.saveCollectBeanList(App.getCollectBeanList());
        }
    }
    private void judgeLoginState() {
        if (App.getUserBean()!=null && App.getUserBean().getIs_verified()==App.PassValue)
        {
            if (goodsDetailBean!=null && goodsDetailBean.getAmount().equals("0"))
            {
                textViewAddCart.setText("补货申请登记");
                textViewAddCart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent =new Intent(GoodsDetailsActivity.this,CheckBugGoodsActivity.class);
                        intent.putExtra(TagGoodsDetailBean,goodsDetailBean);
                        startActivity(intent);
                    }
                });
                textViewBuyNow.setVisibility(View.GONE);
            }else
            {
                textViewAddCart.setText("加入购物车");
                textViewBuyNow.setText("立刻购买");
            }
        }else {
            textViewAddCart.setText("认证方可订购");
            textViewAddCart.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (App.getUserBean()==null)
                    {
                        Intent intent=new Intent(GoodsDetailsActivity.this, LoginActivity.class);
                        startActivity(intent);
                        return;
                    }else if (App.getUserBean()!=null && App.getUserBean().getIs_verified()!=App.PassValue)
                    {
                        Intent intent=new Intent(GoodsDetailsActivity.this,StoreManagerActivity.class);
                        startActivity(intent);
                        return;
                    }


                }
            });
            textViewBuyNow.setVisibility(View.GONE);
        }
    }

    public void onEventMainThread(UpdateShopCarRedCount updateShopCarRedCount) {

        GBaseActivity.RefreshShopCarRedCount(textViewShopCarCount,relativeLayoutShopCar);

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        if (positionOffsetPixels != 0 && position == 0) {
         //   imageViewGreenLine.setTranslationX((float) positionOffsetPixels / 2);
            imageViewGreenLine.setTranslationX(AbViewUtil.scaleValue(getActivity(),150)*positionOffset);
          //  Log.e("position == 0",positionOffset+"");
          //  temp = imageViewGreenLine.getX();
            //System.out.println("temp: " + temp);
        } else if (positionOffsetPixels != 0 && position == 1) {
            if (AbViewUtil.scaleValue(getActivity(),150)*positionOffset> AbViewUtil.scaleValue(getActivity(),100)) {
                imageViewGreenLine.setTranslationX(AbViewUtil.scaleValue(getActivity(), 150) * positionOffset);
            }
          //  Log.e("position == 1",positionOffset+"");
           // temp = imageViewGreenLine.getX();
        }
    }

    @Override
    public void onPageSelected(int position) {
       /* if (position==0)
        {
            changeTextViewColor(textViewShangPing);
        }else if (position==1)
        {
            changeTextViewColor(textViewXiangQing);
        }*/
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
    private void changeTextViewColor(TextView textView)
    {

        /*textViewShangPing.setTextColor(getResources().getColor(R.color.color_666666));
        textViewXiangQing.setTextColor(getResources().getColor(R.color.color_666666));
        textView.setTextColor(getResources().getColor(R.color.color_37c4a4));*/
    }

    public class GoodsFragmentAdapter extends FragmentPagerAdapter {
        public static final int COUNT = 2;
        public ArrayList<Fragment> list;
        public GoodsFragmentAdapter(FragmentManager fm) {
            super(fm);
        }
        public GoodsFragmentAdapter(FragmentManager fm, ArrayList<Fragment> list){
            super(fm);
            this.list = list;
        }

        @Override
        public Fragment getItem(int position) {
            return list.get(position);
        }

        @Override
        public int getCount() {
            return list.size();
        }
    }

    private void TaskCollectGoods(final boolean isloadmore) {
        RequestServerManager.getInstanceDIY().handleMethodDIY((GBaseActivity) getActivity(), null, isloadmore, null,
                Constant.getRootUrl() + Constant.Action.Action_CollectGoods, Constant.Action.Action_CollectGoods, RequestServerManager.getInstanceDIY().
                        getRequestParams(Constant.Action.Action_CollectGoods,App.getUserBean().getUserid(),App.getUserBean().getSession_id(),itemID), BaseResponse.class, new ICallBackForRequestServer<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse result) {
                        MainActivity.TaskGetCollectData(false);
                        CollectBean collectBean=new CollectBean();
                        collectBean.setItemid(goodsDetailBean.getItemid());
                        App.getCollectBeanListServer().add(collectBean);
                        imageViewShouCang.setImageResource(R.drawable.icon_love);
                        SweetDialogManager.getInstance().showDialogBySuccessTitleText(GoodsDetailsActivity.this, "收藏成功", "", false, false, new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                //判断是否已收藏



                                sweetAlertDialog.dismiss();
                            }
                        });
                    }

                    @Override
                    public void onFail(int type, String errorMsg, String json) {
                        Intent intent=new Intent(GoodsDetailsActivity.this,MainActivity.class);
                        startActivity(intent);
                    }
                });
    }
}

